package ru.spbu.math.seabattle.server.jms;

import javax.jms.MessageListener;

import org.apache.activemq.broker.BrokerService;

import ru.spbu.math.seabattle.client.jms.common.JmsQueueHelper;

/**
 * 
 * Not really abstract yet, but could be in the future
 *
 */
public abstract class AbstractJMSServer implements MessageListener {
	
	protected final String brokerAddress;
	protected final BrokerService broker;
	protected final String quoteProviderTopicName;
	protected volatile boolean started = false;
	protected JmsQueueHelper handshakeQueue;

	public AbstractJMSServer(String url, String serverName, String quoteProviderTopicName) {
		this.brokerAddress = url;
		this.quoteProviderTopicName = quoteProviderTopicName;
		broker = new BrokerService();
		broker.setBrokerName(serverName);
		broker.setUseShutdownHook(false);
	}
	
	public void start() throws Exception {
		broker.addConnector(brokerAddress);
		broker.start();
		
		handshakeQueue = new JmsQueueHelper();
		handshakeQueue.start(brokerAddress, quoteProviderTopicName);
		
		handshakeQueue.addMessageListener(this);
		
		started = true;
	}
	
	public void shutdown() throws Exception {
		handshakeQueue.shutdown();
		broker.stop();
		started = false;
	}
	
	public boolean isUpAndRunning() {
		return started;
	}
}
